// pages/Case/caseDetail/caseDetail.js
import request from '../../../utils/config.js';
import util from '../../../utils/util.js';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    caseInfo:{},
    current: 0,
    SearchOper: false,
    searchValue:'',
    searchTag:[],
    tempOperList:[],//用于清空搜索值
    typename: '',
    caseId:'',
    operList: [],
    roles_Trace: false,
    roles_Market: false,
    roles_Risk: false,
    no_Manage:false,  
    flagType:'' ,
    showHomeBtn:false,
    showModel:false
  },

  clickTab1: function () {
    this.setData({
      current:  0
    })
  },
  clickTab2: function () {
    this.setData({
      current: 1
    })
  },

  //check CommonData
  checkCommonData:function(list){
    // list = list.reverse();
    let temArr = new Array();
    list.forEach(function(e){
      let day = util.timetrans(e.finishTime,'day');
      let time = util.timetrans(e.finishTime, 'time');
      let dateHM = time.substring(0,5);
      let dateMD = day.substring(5) ;
      e.dateMD = dateMD;
      e.dateHM = dateHM;
      e.trackDesc = e.recordText;
      temArr.push(e)
    });
    // for (var i = list.length - 1; i >= 0; i--) {
    //   let day = util.timetrans(list[i].finishTime, 'day');
    //   let time = util.timetrans(list[i].finishTime, 'time');
    //   let dateHM = time.substring(0, 5);
    //   let dateMD = day.substring(5);
    //   list[i].dateMD = dateMD;
    //   list[i].dateHM = dateHM;
    //   list[i].trackDesc = list[i].recordText;
    //   temArr.push(list[i])
    // } 
    return temArr;
  },


  getDetail:function(){
    let _this = this;
    wx.showLoading({title: ' ', mark:true})
    request.requestMisApi("get", "caseBaseInfos/query4Wx/"+this.data.caseId, {}, (res) => {
      wx.hideLoading();
      if (res.code='00') {
        let info = JSON.parse(res.body)
        let lawsuitStepRecordList = [], enforceStepRecordList = [];
        info.caseBaseInfoVo.caseAmtStr = util.filterFormatAmt(info.caseBaseInfoVo.caseAmt * 1 / 10000);
        info.caseBaseInfoVo.statusStr = util.checkStatus(info.caseBaseInfoVo.status);
        info.caseBaseInfoVo.applyDateStr = util.dateStr(info.caseBaseInfoVo.applyDate);
        info.caseTrackRecords.map((item)=>{
          item.dateHM = item.operTime.substring(0, 2) + ':' + item.operTime.substring(2, 4)
          item.dateMD = item.operDate.substring(4, 6) + '-' + item.operDate.substring(6,8);
        })
        console.log("案件详情=",info)
        try{
          if (info.lawsuitStepRecordWithBLOBVos){
            if (info.lawsuitStepRecordWithBLOBVos.length > 0) {
              lawsuitStepRecordList = _this.checkCommonData(info.lawsuitStepRecordWithBLOBVos);
            }
          }
          if (info.enforceStepRecordWithBLOBsVos){
            if (info.enforceStepRecordWithBLOBsVos.length > 0) {
              enforceStepRecordList = _this.checkCommonData(info.enforceStepRecordWithBLOBsVos);
            }
          }
          if (info.enforceStepRecordWithBLOBsVos|| info.lawsuitStepRecordWithBLOBVos) {
            roles_Trace = false;
          }
        }catch(e){
          console.log("案件列表兼容性处理报错")
          try{
            if (info.enforceCurrInfoVo || info.lawsuitCurrInfo) {
              roles_Trace = false;
            }
          }catch(e){

          }
          
        }
        
        let { roles_Trace, no_Manage} = _this.data
        if (info.caseBaseInfoVo.status == util.filter.getStatusStr('案件', '已提交') ||
          info.caseBaseInfoVo.status == util.filter.getStatusStr('案件', '未提交') ||
          info.caseBaseInfoVo.status == util.filter.getStatusStr('案件', '已关闭') ||
          info.caseBaseInfoVo.status == util.filter.getStatusStr('案件', '异常结案') ||
          info.caseBaseInfoVo.status == util.filter.getStatusStr('案件', '已结案')) {
          roles_Trace = false;
        }
        
        if (!info.caseManageInfoVo.callOperId && !info.caseManageInfoVo.saleOperId && !info.caseManageInfoVo.serviceOperId && !info.caseManageInfoVo.rmChargerId && !info.caseManageInfoVo.rmDealId && !info.caseManageInfoVo.rmOperId && !info.caseManageInfoVo.signChargerName){
          no_Manage=true;
        }

        let contactList = enforceStepRecordList.concat(lawsuitStepRecordList, info.caseTrackRecords)
        info.caseTrackRecords = contactList;
        _this.setData({ caseInfo: info, roles_Trace, no_Manage})
      } else {
        wx.showToast({ title: '获取失败', icon: 'none', duration: 1000 });
      }
    }, (res) => {
      wx.hideLoading();
      console.log("获取失败", res)
    });
  },
  swiperChange: function (e) {
    // console.log(e)
    if (e.detail.source == "touch") {
      this.setData({ current: e.detail.current })
    }
  },
  addClientMsg: function () {
    app.globalData.caseTrackInfo = this.data.caseInfo
    wx.navigateTo({
      url: '../addTrack/addTrack',
    })
  },

  select: function (e) {
    let selectInfo = e.detail
    if (selectInfo) {
      this.setData({ searchValue:''})
      selectInfo = JSON.parse(selectInfo)
      console.log(selectInfo) 
      let typename = this.data.typename;
      let caseManageInfoVo = this.data.caseInfo.caseManageInfoVo
      if (typename == 'callOperName' || typename == 'saleOperName' || typename == 'serviceOperName') {
        if (this.data.roles_Market) {
          let send={
            caseId: this.data.caseId,
            callOperId: caseManageInfoVo.callOperId,
            callOperName: caseManageInfoVo.callOperName,
            saleOperId: caseManageInfoVo.saleOperId,
            saleOperName: caseManageInfoVo.saleOperName,
            serviceOperId: caseManageInfoVo.serviceOperId,
            serviceOperName: caseManageInfoVo.serviceOperName,
            signChargerId: caseManageInfoVo.signChargerId,
            signChargerName: caseManageInfoVo.signChargerName
          }
          if (typename == 'callOperName'){
            send.callOperId = selectInfo.operId;
            send.callOperName = selectInfo.realName;
          } else if (typename == 'saleOperName') {
            send.saleOperId = selectInfo.operId;
            send.saleOperName = selectInfo.realName;
          } else if (typename == 'serviceOperName') {
            send.serviceOperId = selectInfo.operId;
            send.serviceOperName = selectInfo.realName;
          }
          console.log(send)
          let _this = this;
          wx.showLoading({ title: ' ', mask: true })
          request.requestMisApi("put",'caseManageInfos/bizNotifies', send, (res) => {
            console.log("修改", res)
            wx.hideLoading()
            if (res.code == '00') {
              _this.getDetail()
              wx.showToast({
                title: res.msg,
                icon: 'success',
                duration: 1000
              })
            } else {
              wx.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
              })
            }
          }, (res) => {
            console.log("获取失败", res)
          });
        }
      } else if (typename == 'rmChargerName' || typename == 'rmDealName' || typename == 'rmOperName') {
        if (this.data.roles_Risk) {
          let send = {
            caseId: this.data.caseId,
            rmChargerId: caseManageInfoVo.rmChargerId,
            rmChargerName: caseManageInfoVo.rmChargerName,
            rmDealId: caseManageInfoVo.rmDealId,
            rmDealName: caseManageInfoVo.rmDealName,
            rmOperId: caseManageInfoVo.rmOperId,
            rmOperName: caseManageInfoVo.rmOperName,
            signChargerId: caseManageInfoVo.signChargerId,
            signChargerName: caseManageInfoVo.signChargerName
          }
          if (typename == 'rmChargerName') {
            send.rmChargerId = selectInfo.operId;
            send.rmChargerName = selectInfo.realName;
          } else if (typename == 'rmDealName') {
            send.rmDealId = selectInfo.operId;
            send.rmDealName = selectInfo.realName;
          } else if (typename == 'rmOperName') {
            send.rmOperId = selectInfo.operId;
            send.rmOperName = selectInfo.realName;
          }
          console.log(send)
          let _this = this;
          wx.showLoading({ title: ' ', mask: true })
          request.requestMisApi("put", 'caseManageInfos/riskNotifies', send, (res) => {
            console.log("修改", res)
            wx.hideLoading()
            if (res.code == '00') {
              _this.getDetail()
              wx.showToast({
                title: res.msg,
                icon: 'success',
                duration: 1000
              })
            } else {
              wx.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
              })
            }
          }, (res) => {
            console.log("获取失败", res)
          });
        }
      }
    }
  },
  getOpers: function () {
    if (this.data.operList.length>0){
      return
    }
    let _this = this;
    request.requestMisApi("get", "opers/noAuths", { status: '0' }, (res) => {
      if (res) {
        console.log(res)
        _this.setData({ operList: res })
      }
    }, (res) => {
      console.log("获取失败", res)
    });
  },
  SearchOperTap:function(e){
    let typename = e.currentTarget.dataset.typename;
    this.setData({ typename, searchTag: [], searchValue: '', tempOperList:[]});
    if (typename == 'callOperName' || typename == 'saleOperName' || typename == 'serviceOperName'){
      if (this.data.roles_Market){
        this.setData({ SearchOper: true })
      }
      if (typename == 'callOperName' || typename == 'saleOperName'){
        this.setData({ searchTag: [{ type: 'all'}]})
      } else if (typename == 'serviceOperName'){
        this.setData({ searchTag: [{type: 'tags', value: ['SERVICE_OPER']}]})
      }
    } else if (typename == 'rmChargerName' || typename == 'rmDealName' || typename == 'rmOperName'){
      if (this.data.roles_Risk) {
        this.setData({ SearchOper: true, searchTag: [{ type: 'tags', value: ['LAWYER'] }]})
      }
    }

  },
  // 收藏取消
  collect: function () {
    if (this.data.isloading) {
      return
    }
    this.setData({
      isloading: true
    });
    let _this = this;
    if (this.data.caseInfo.caseBaseInfoVo.isFavor == "Y") {
      request.requestMisApi('get', "flyWorkPlace/unfavorCases/" + this.data.caseId, {}, (res) => {
        console.log(res)
        if (res.code == '00') {
          let caseInfo = this.data.caseInfo;
          caseInfo.caseBaseInfoVo.isFavor='N';
          _this.setData({
            isloading: false, caseInfo
          });
        }
      }, (res) => {
        console.log("接口错误=", res)
      });
    } else {
      request.requestMisApi('get', "flyWorkPlace/favorCases/" + this.data.caseId, {}, (res) => {
        console.log(res)
        if (res.code == '00') {
          let caseInfo = this.data.caseInfo;
          caseInfo.caseBaseInfoVo.isFavor = 'Y';
          _this.setData({
            isloading: false, caseInfo
          });
        }
      }, (res) => {
        console.log("接口错误=", res)
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("options=====",options)
    let flagType = "";
    let showHomeBtn = false;
    if(options.flag){
      flagType = options.flag;
    }else{
      showHomeBtn = true;
    }
    this.setData({
       caseId:options.caseId,
       flagType: flagType,
       showHomeBtn: showHomeBtn
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.toast = this.selectComponent("#toast");
    this.homeBtn = this.selectComponent("#homeBtn");
  },

  //组件授权回调
  _setAuthorization: function (e) {
    let that = this;
    that.getOpenid(that);
  },

  //点击返回首页组件回调
  _goHomeBtn: function (e) {
    wx.setStorageSync("flagName", "caseTrack");
    wx.redirectTo({
      url: '../caseIndex/caseIndex?flagName=caseTrack'
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (!wx.getStorageSync('token')) {
      //未登录
      wx.showModal({
        title: '未登录',
        content: '请先登录系统',
        confirmText: '前去登录',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '../../index/index',
            })
          } else if (res.cancel) {
          }
        }
      })
      return
    }
    //判断案件进入的场景（列表进入、推送消息进入）
    if (app.globalData.userInfo && this.data.flagType) {//列表进入
      this.setData({
        roles_Trace: app.globalData.loginUserInfo.roles.includes('ROLE_CaseTrace'),
        roles_Market: app.globalData.loginUserInfo.roles.includes('ROLE_CaseManage4Market'),
        roles_Risk: app.globalData.loginUserInfo.roles.includes('ROLE_CaseManage4Risk'),
      });
      this.getDetail()
      this.getOpers()
    } else {//消息推送
      let _that = this;
      if (!app.globalData.userInfo) {//判断是否登录过
        app.getAuthUserInfo((res) => {
          res.userInfo.nickName = res.userInfo.nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
          app.globalData.userInfo = res.userInfo;
          app.globalData.encryptedData = res.encryptedData;
          app.globalData.iv = res.iv;
          _that.getOpenid(_that);
        }, (res) => {
          _that.setData({
            showModel: true
          })
        });
      } else {//已登录
        this.setData({
          roles_Trace: app.globalData.loginUserInfo.roles.includes('ROLE_CaseTrace'),
          roles_Market: app.globalData.loginUserInfo.roles.includes('ROLE_CaseManage4Market'),
          roles_Risk: app.globalData.loginUserInfo.roles.includes('ROLE_CaseManage4Risk'),
        });
        this.getDetail()
        this.getOpers()
      }
    }  
  },

  //获取openid
  getOpenid: (_that) => {
    app.getGlobalOpenid(function (token) {
      if (token) {
        //开始校验看token值
        _that.checkToken();
      } else {
        wx.hideLoading();
        //未登录
        wx.showModal({
          title: '未登录',
          content: '请先登录系统',
          confirmText: '前去登录',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../../index/index',
              })
            } else if (res.cancel) {
            }
          }
        })
      }
    });
  },

  //检验token值
  checkToken: function () {
    let _that = this;
    app.checkGlobalToken(function (res) {
      _that.setData({
        loginUserInfo: res.loginUserInfo,
      });
      let tempList = res.tempList;
      let flagName = res.flagName;
      let jurisdiction = res.jurisdiction;
      let roleQuanxian = res.roleQuanxian;
      let department = res.department;
      if (tempList.length == 0) {
        wx.showModal({
          title: '对不起',
          content: '您的权限不足',
          confirmText: "知道了",
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../../index/index',
              })
            } else if (res.cancel) {
            }
          }
        })
        return;
      }

      //校验上次记住的部门权限是否还存在
      if (jurisdiction.indexOf(roleQuanxian) < 0) {
        wx.showModal({
          title: '对不起',
          content: "您的" + department + "权限不足",
          confirmText: "知道了",
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../../index/index',
              })
            } else if (res.cancel) {
            }
          }
        })
        return;
      }
      _that.setData({
        roles_Trace: app.globalData.loginUserInfo.roles.includes('ROLE_CaseTrace'),
        roles_Market: app.globalData.loginUserInfo.roles.includes('ROLE_CaseManage4Market'),
        roles_Risk: app.globalData.loginUserInfo.roles.includes('ROLE_CaseManage4Risk'),
      });
      _that.getDetail()
      _that.getOpers()
    }, function (res) {
      //登录超时
      wx.showModal({
        title: '登录超时',
        content: '点击确定重新登录',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '../../index/index',
            })
          } else if (res.cancel) {
          }
        }
      })
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getDetail()
    setTimeout(function () {
      wx.stopPullDownRefresh();
    }, 500);
    console.log("执行了一次下拉刷新")
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

 //转发
  // onShareAppMessage: function (res) {
  //   if (res.from === 'button') {
  //     // 来自页面内转发按钮
  //     console.log("来自页面内的转发", res.target)
  //   }
  //   let This = this;
  //   return {
  //     title: "转发测试",
  //     path: 'pages/Case/caseDetail/caseDetail?caseId=' + This.data.caseId,

  //     success: function (res) {
  //       // 转发成功
  //       console.log("转发成功返回数据=", res)
  //       wx.showShareMenu({
  //         // 要求小程序返回分享目标信息
  //         withShareTicket: true
  //       });

  //       if (res.shareTickets) {
  //         // 获取转发详细信息
  //         wx.getShareInfo({
  //           shareTicket: res.shareTickets[0],
  //           success(res) {

  //           },
  //           fail() { },
  //           complete() { }
  //         });
  //       }
  //     },
  //     fail: function (res) {
  //       // 转发失败
  //     },
  //     complete: function () {

  //     }
  //   }
  // },
})